#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import absolute_import, division, print_function, unicode_literals

__license__   = 'GPL v3'
__copyright__ = '2019, Peter Liu'
__docformat__ = 'restructuredtext en'

if False:
    # This is here to keep my python error checker from complaining about
    # the builtin functions that will be defined by the plugin loading system
    # You do not need this code in your plugins
    get_icons = get_resources = None

from PyQt5.Qt import QDialog, QVBoxLayout, QPushButton, QMessageBox, QLabel, QLineEdit

from calibre_plugins.title_seperator_itpansic.config import prefs
import re

class DemoDialog(QDialog):

    def __init__(self, gui, icon, do_user_config):
        QDialog.__init__(self, gui)
        self.gui = gui
        self.do_user_config = do_user_config

        # The current database shown in the GUI
        # db is an instance of the class LibraryDatabase from db/legacy.py
        # This class has many, many methods that allow you to do a lot of
        # things. For most purposes you should use db.new_api, which has
        # a much nicer interface from db/cache.py
        self.db = self.gui.library_view.model().db

        self.l = QVBoxLayout()
        self.setLayout(self.l)

        self.label = QLabel("输入正则表达式，将书名命名为\n?\P<title\>\n将作者命名为\n?\P<author\>\n例如，书名为\n《三国演义》（校对版全本）作者：罗贯中\n对应正则表达式为\n《(?\P<title\>.*)》（校对版全本）作者：(?\P<author\>.*)")
        self.l.addWidget(self.label)

        self.setWindowTitle('从书名读取 书名、作者')
        self.setWindowIcon(icon)

		self.msg = QLineEdit(self)
        self.msg.setText(prefs['hello_world_msg'])
		self.msg.textChanged.connect(self.text_changed)
        self.l.addWidget(self.msg)
		
        self.update_metadata_button = QPushButton(
            '分解(&m)', self)
        self.update_metadata_button.clicked.connect(self.update_metadata)
        self.l.addWidget(self.update_metadata_button)

        self.resize(self.sizeHint())

    def update_metadata(self):
        '''
        Set the metadata in the files in the selected book's record to
        match the current metadata in the database.
        '''
        from calibre.ebooks.metadata.meta import set_metadata
        from calibre.gui2 import error_dialog, info_dialog

        # Get currently selected books
        rows = self.gui.library_view.selectionModel().selectedRows()
        if not rows or len(rows) == 0:
            return error_dialog(self.gui, 'Cannot update metadata',
                             'No books selected', show=True)
        # Map the rows to book ids
        ids = list(map(self.gui.library_view.model().id, rows))
        db = self.db.new_api
		count = 0
        for book_id in ids:
            # Get the current metadata for this book from the db
            mi = db.get_metadata(book_id, get_cover=False, cover_as_data=False)
			print ("-----------before---" + str(mi))
			result = re.match(prefs['hello_world_msg'], mi.title)
			print ("-----------result---" + str(result))
			if not result:
				continue
			if not result.group('title'):
				continue
			count = count + 1
			mi.title = result.group('title')
			mi.title_sort = result.group('title')
			if result.group('author'):
				mi.authors = [result.group('author')]
				mi.author_sort = result.group('author')

			print ("-----------after---" + str(mi))
            fmts = db.formats(book_id)
			
            if not fmts:
                continue
            for fmt in fmts:
                fmt = fmt.lower()
                # Get a python file object for the format. This will be either
                # an in memory file or a temporary on disk file
                ffile = db.format(book_id, fmt, as_file=True)
                ffile.seek(0)
				
                # Set metadata in the format
                set_metadata(ffile, mi, fmt)
                ffile.seek(0)
                # Now replace the file in the calibre library with the updated
                # file. We dont use add_format_with_hooks as the hooks were
                # already run when the file was first added to calibre.
			db.set_metadata(book_id, mi, force_changes=True,)
        info_dialog(self, 'Updated files',
                '成功 '+str(count)+' ,  失败 ' + str(len(ids) - count),
                show=True)

    def config(self):
        self.do_user_config(parent=self)
        # Apply the changes
        self.label.setText(prefs['hello_world_msg'])
		
	def text_changed(self, text):
        prefs['hello_world_msg'] = text
		#self.label.setText(prefs['hello_world_msg'])
